import datetime

from playhouse.shortcuts import model_to_dict
from model import Process as ModelProcess
from model import Project as ModelProject
from model import Mysql
import utils.jsonData as JsonData
from entity.Prosumer import PRODUCER, CONSUMER
from utils.prosumer_task import *
from service import logService


def query_running_project():
    """查询运行的项目"""
    _res = ModelProcess.Process.select()
    _list = []
    em_id = 0
    for i in _res:
        _dict = model_to_dict(i)
        if _dict["project_id"] is None:
            continue
        em_id += 1
        _dict["em_id"] = em_id
        _dict["name"] = _dict["project_id"]["name"]
        _dict["update_time"] = _dict["project_id"]["update_time"]
        _list.append(_dict)
    return JsonData.JsonData().success_data(msg="查询信息成功", data=_list)


def stop_local_process(_json, log_id=False):
    project_id = _json["project"]
    process_id = _json["process"]
    if (ModelProject.Project.update({
        ModelProject.Project.id: project_id,
        ModelProject.Project.status: False,
        ModelProject.Project.update_time: datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
    }).where(
        ModelProject.Project.id == project_id).execute() and
            ModelProcess.Process.update({
                ModelProcess.Process.project_id: None
            }).where(
                ModelProcess.Process.id == process_id).execute()):
        if log_id:
            logService.update_log_end_time(log_id)
        return JsonData.JsonData().success_data(msg="已终止这个脚本任务！")
    Mysql.db.rollback()
    return JsonData.JsonData().error(code="1008", msg="更新项目状态失败，请重试！")


def get_consumer(ip):
    """根据ip在消费者队列中去获取操作"""
    _res = CONSUMER.pop(ip)
    if not _res:
        return {
            "code": "11001",
            "msg": "没有找到指令"
        }
    return _res
